<template>
  <el-dialog
    v-model="dialogVisible"
    title="文档详情"
    width="80%"
    :before-close="handleClose"
  >
    <div v-loading="loading" class="document-detail">
      <div v-if="documentData" class="detail-content">
        <!-- 基本信息 -->
        <div class="info-section">
          <h3 class="section-title">基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="文档标题">
              <span class="title-text">{{ documentData.title }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="文档类型">
              <el-tag :type="getDocTypeTagType(documentData.docType)">
                {{ DOC_TYPES[documentData.docType] }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="文档来源">
              {{ documentData.source }}
            </el-descriptions-item>
            <el-descriptions-item label="发布日期">
              {{ documentData.publishDate }}
            </el-descriptions-item>
            <el-descriptions-item label="关键词">
              <div class="keywords">
                <el-tag
                  v-for="keyword in keywordList"
                  :key="keyword"
                  size="small"
                  style="margin-right: 5px; margin-bottom: 5px;"
                >
                  {{ keyword }}
                </el-tag>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ documentData.createTime }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 标签信息 -->
        <div v-if="documentData.tags && documentData.tags.length > 0" class="info-section">
          <h3 class="section-title">相关标签</h3>
          <div class="tags-container">
            <div
              v-for="tag in documentData.tags"
              :key="tag.id"
              class="tag-item"
            >
              <el-tag 
                :color="tag.color"
                :style="{ color: getTextColor(tag.color) }"
                size="large"
                class="custom-tag"
              >
                {{ tag.name }}
              </el-tag>
              <span class="tag-usage">使用次数: {{ tag.usageCount }}</span>
            </div>
          </div>
        </div>

        <!-- 文档文件信息 -->
        <div v-if="documentData.fileUrl" class="info-section">
          <h3 class="section-title">文档文件</h3>
          <div class="file-section">
            <div class="file-info-bar">
              <div class="file-basic-info">
                <el-icon class="file-icon" :size="28"><Document /></el-icon>
                <div class="file-text-info">
                  <span class="file-name">{{ fileInfo.fileName }}</span>
                  <span class="file-type-badge">{{ fileInfo.fileType?.toUpperCase() }}</span>
                </div>
              </div>
              <div class="file-actions">
                <el-button 
                  type="primary" 
                  size="small"
                  @click="handlePreview"
                >
                  <el-icon><View /></el-icon>
                  预览文件
                </el-button>
                <el-button 
                  type="success" 
                  size="small"
                  @click="handleDownload"
                >
                  <el-icon><Download /></el-icon>
                  下载文件
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 文档内容 -->
        <div class="info-section">
          <h3 class="section-title">文档内容</h3>
          <div class="content-container">
            <div class="content-text">
              {{ documentData.content }}
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleEdit">
          <el-icon><Edit /></el-icon>
          编辑文档
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Edit, Document, View, Download } from '@element-plus/icons-vue'
import { getDocumentDetail, DOC_TYPES, getDocumentPreviewUrl } from '../../../api/document'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  documentId: {
    type: [Number, String],
    default: null
  }
})

const emit = defineEmits(['update:visible', 'edit'])

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 加载状态
const loading = ref(false)

// 文档数据
const documentData = ref(null)

// 文件预览相关（已简化为新窗口打开）

// 从 fileUrl 中提取文件信息
const fileInfo = computed(() => {
  if (!documentData.value?.fileUrl) {
    return {
      fileName: '',
      fileType: '',
      objectName: ''
    }
  }
  
  const url = documentData.value.fileUrl
  
  // 提取文件名（URL最后一个/后面的部分）
  const fileName = url.substring(url.lastIndexOf('/') + 1)
  
  // 提取文件类型（扩展名，去掉点号）
  const fileType = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase()
  
  // 提取 objectName（从bucket名称后面开始的路径）
  // 例如：http://192.168.150.101:9000/legal-literature/documents/1/xxx.docx
  // objectName 应该是：documents/1/xxx.docx
  let objectName = ''
  try {
    const urlObj = new URL(url)
    const pathname = urlObj.pathname
    // 去掉开头的 /legal-literature/
    const bucketIndex = pathname.indexOf('/', 1)
    if (bucketIndex !== -1) {
      objectName = pathname.substring(bucketIndex + 1)
    }
  } catch (e) {
    console.error('解析URL失败:', e)
  }
  
  return {
    fileName,
    fileType,
    objectName
  }
})

// 关键词列表（将逗号分隔的字符串转换为数组）
const keywordList = computed(() => {
  if (!documentData.value?.keywords) return []
  return documentData.value.keywords.split(',').filter(k => k.trim())
})

// 获取文档类型标签样式
const getDocTypeTagType = (docType) => {
  const typeMap = {
    0: 'danger',   // 法律 - 红色
    1: 'primary',  // 案例 - 蓝色
    2: 'warning',  // 判决书 - 橙色
    3: 'success'   // 文章 - 绿色
  }
  return typeMap[docType] || 'info'
}

// 计算文字颜色（根据背景色深浅）
const getTextColor = (backgroundColor) => {
  if (!backgroundColor) return '#333'
  
  // 去掉#号
  const hex = backgroundColor.replace('#', '')
  
  // 转换为RGB
  const r = parseInt(hex.substr(0, 2), 16)
  const g = parseInt(hex.substr(2, 2), 16)
  const b = parseInt(hex.substr(4, 2), 16)
  
  // 计算亮度
  const brightness = (r * 299 + g * 587 + b * 114) / 1000
  
  // 根据亮度返回黑色或白色文字
  return brightness > 128 ? '#333' : '#fff'
}

// 获取文档详情
const fetchDocumentDetail = async () => {
  if (!props.documentId) return
  
  loading.value = true
  try {
    const response = await getDocumentDetail(props.documentId)
    if (response.code === 200) {
      documentData.value = response.data
    } else {
      ElMessage.error('获取文档详情失败')
    }
  } catch (error) {
    console.error('获取文档详情失败:', error)
    ElMessage.error('获取文档详情失败')
  } finally {
    loading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  documentData.value = null
  emit('update:visible', false)
}

// 编辑文档
const handleEdit = () => {
  emit('edit', documentData.value)
  handleClose()
}

// ==================== 文件预览和下载 ====================

// 预览文件 - 在新窗口打开
const handlePreview = async () => {
  if (!fileInfo.value.objectName) {
    ElMessage.warning('文件路径不存在')
    return
  }
  
  try {
    // 显示加载提示
    const loadingMsg = ElMessage.info('正在获取预览链接...')
    
    // 调用后端接口获取预览URL
    const response = await getDocumentPreviewUrl(fileInfo.value.objectName)
    
    loadingMsg.close()
    
    if (response.code === 200) {
      const previewUrl = response.data.previewUrl
      
      // 在新窗口打开
      window.open(previewUrl, '_blank')
      ElMessage.success('已在新窗口打开预览')
      
      // 如果后端返回了提示信息，显示出来
      if (response.data.tip) {
        ElMessage.info(response.data.tip)
      }
    } else {
      ElMessage.error(response.message || '获取预览URL失败')
    }
  } catch (error) {
    console.error('获取预览URL失败:', error)
    ElMessage.error('获取预览URL失败，请重试')
  }
}


// 下载文件 - 直接使用fileUrl下载
const handleDownload = () => {
  if (!documentData.value?.fileUrl) {
    ElMessage.warning('文件路径不存在')
    return
  }
  
  // 创建隐藏的a标签进行下载
  const link = document.createElement('a')
  link.href = documentData.value.fileUrl
  link.download = fileInfo.value.fileName || 'document'
  // 移除 target="_blank"，在当前窗口下载
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  
  ElMessage.success('开始下载')
}

// 监听documentId变化，获取详情
watch(() => props.documentId, (newId) => {
  if (newId && props.visible) {
    fetchDocumentDetail()
  }
}, { immediate: true })

// 监听对话框打开
watch(() => props.visible, (visible) => {
  if (visible && props.documentId) {
    fetchDocumentDetail()
  }
})
</script>

<style scoped>
.document-detail {
  min-height: 300px;
}

.detail-content {
  padding: 0 10px;
}

.info-section {
  margin-bottom: 30px;
}

.section-title {
  margin: 0 0 15px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  border-left: 4px solid #409EFF;
  padding-left: 10px;
}

.title-text {
  font-weight: 600;
  font-size: 16px;
  color: #333;
}

.keywords {
  line-height: 1.8;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.tag-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background-color: #f8f9fa;
}

.tag-usage {
  margin-top: 5px;
  font-size: 12px;
  color: #666;
}

.custom-tag {
  border: none;
  font-weight: 600;
}

.content-container {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background-color: #fafafa;
  padding: 20px;
  max-height: 400px;
  overflow-y: auto;
}

.content-text {
  line-height: 1.8;
  font-size: 14px;
  color: #333;
  white-space: pre-wrap;
  word-break: break-word;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-descriptions__label) {
  width: 120px;
  font-weight: 600;
}

:deep(.el-descriptions__content) {
  word-break: break-word;
}

/* 滚动条样式 */
.content-container::-webkit-scrollbar {
  width: 6px;
}

.content-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.content-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.content-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 文件相关样式 */
.file-section {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 0;
  overflow: hidden;
}

.file-info-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
}

.file-basic-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.file-icon {
  color: #409eff;
}

.file-text-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.file-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  word-break: break-all;
}

.file-type-badge {
  display: inline-block;
  padding: 4px 10px;
  background-color: #409eff;
  color: #fff;
  font-size: 12px;
  font-weight: 600;
  border-radius: 4px;
  width: fit-content;
}

.file-actions {
  display: flex;
  gap: 10px;
}

.file-preview-container {
  background-color: #fff;
}

.preview-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

.preview-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.preview-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.preview-content {
  padding: 0;
  min-height: 600px;
  background-color: #fff;
  position: relative;
}

.pdf-preview-wrapper {
  position: relative;
  width: 100%;
  height: 600px;
}

.preview-iframe {
  width: 100%;
  height: 100%;
  border: none;
}

.iframe-error {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  gap: 15px;
  z-index: 10;
}

.iframe-error .el-icon {
  color: #e6a23c;
}

.error-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  color: #303133;
}

.error-desc {
  font-size: 14px;
  margin: 0;
  color: #606266;
}

.error-actions {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.preview-unsupported {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 40px;
  gap: 20px;
  color: #909399;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.preview-unsupported .el-icon {
  color: #409eff;
}

.unsupported-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0;
  color: #303133;
}

.unsupported-desc {
  font-size: 14px;
  margin: 0;
  color: #606266;
  text-align: center;
  line-height: 1.6;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .detail-content {
    padding: 0 5px;
  }
  
  .tags-container {
    gap: 10px;
  }
  
  .tag-item {
    padding: 8px;
  }
  
  .content-container {
    padding: 15px;
  }
  
  .file-info-bar {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .file-actions {
    width: 100%;
    flex-direction: column;
  }
  
  .file-actions .el-button {
    width: 100%;
  }
  
  .preview-iframe {
    height: 400px;
  }
  
  :deep(.el-descriptions) {
    --el-descriptions-item-bordered-label-background: #fafafa;
  }
}
</style>
